﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using SU.Center.Infa;
using System.Security.Claims;

namespace SU.Center.Api.Controllers
{
    [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly ILogger<UsersController> logger;

        public UsersController(IMediator _mediator, IHttpContextAccessor _contextAccessor, ILogger<UsersController> logger)
        {
            this._mediator = _mediator;
            this._contextAccessor = _contextAccessor;
            this.logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<ApiResult> GetLogin([FromQuery] GetUserLogRepsultDto dto)
        {
            logger.LogInformation("登录");
            return await _mediator.Send(dto);
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public IActionResult GetUserInfo()
        {
            var user = _contextAccessor.HttpContext?.User;

            var userIdClaim = user.FindFirst("userId")?.Value;
            var usernameClaim = user.FindFirst("username")?.Value;

            return Ok(new
            {
                UserId = userIdClaim,
                Username = usernameClaim
            });
        }

    }
}
